package com.ffox.service.impl;

import com.ffox.entity.ForumComment;
import com.ffox.entity.ForumPost;
import com.ffox.mapper.UserForumMapper;
import com.ffox.service.UserForumService;
import com.ffox.service.dto.CommentDto;
import com.ffox.service.dto.PostDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserForumServiceImpl implements UserForumService {

    @Autowired
    private UserForumMapper userForumMapper;
    @Override
    public List<PostDto> getAllPosts() {
        List<ForumPost> posts = userForumMapper.getAllPosts();
        List<PostDto> postDtos = new ArrayList<>();
        for (int i=0; i < posts.size(); i++){
            PostDto postDto = new PostDto();
            postDto.setId(posts.get(i).getId());
            postDto.setUserNum(posts.get(i).getUserNum());
            postDto.setAvatar(userForumMapper.getAvatarByUserNum(posts.get(i).getUserNum()));
            postDto.setTitle(posts.get(i).getTitle());
            postDto.setContent(posts.get(i).getContent());
            postDto.setViewCount(posts.get(i).getViewCount());
            postDto.setReplyCount(posts.get(i).getReplyCount());
            postDto.setCreatedAt(posts.get(i).getCreatedAt());
            postDtos.add(postDto);
        }
        return postDtos;
    }

    @Override
    public Integer addPost(ForumPost post) {
        post.setReplyCount(0);
        post.setViewCount(0);
        post.setCreatedAt(LocalDateTime.now());
        post.setStatus((byte) 0);
        return userForumMapper.addPost(post);
    }

    @Override
    public Integer deletePost(Long postId) {
        return userForumMapper.deletePost(postId);
    }

    @Override
    public List<CommentDto> getComments(Long postId) {
        List<ForumComment> comments = userForumMapper.getComments(postId);
        List<CommentDto> commentDtos = new ArrayList<>();
        for (int i=0; i < comments.size(); i++){
            CommentDto commentDto = new CommentDto();
            commentDto.setId(comments.get(i).getId());
            commentDto.setPostId(comments.get(i).getPostId());
            commentDto.setUserNum(comments.get(i).getUserNum());
            commentDto.setAvatar(userForumMapper.getAvatarByUserNum(comments.get(i).getUserNum()));
            commentDto.setContent(comments.get(i).getContent());
            commentDto.setCreatedAt(comments.get(i).getCreatedAt());
            commentDtos.add(commentDto);
        }

        return commentDtos;
    }

    @Override
    public Integer addComment(ForumComment comment) {
        comment.setCreatedAt(LocalDateTime.now());
        comment.setStatus((byte) 0);
        return userForumMapper.addComment(comment);
    }

    @Override
    public Integer deleteComment(Long commentId) {
        return userForumMapper.deleteComment(commentId);
    }
}
